<template>
  <div class="clock-in-container">
    <!-- 顶部信息区 -->
    <div class="header-info">
      <div class="date-time">
        <div class="time">{{ currentTime }}</div>
        <div class="date">{{ currentDate }}</div>
      </div>
      <div class="user-info">
        <img :src="userAvatar" class="avatar" />
        <span class="username">{{ userName }}</span>
      </div>
    </div>

    <!-- 打卡按钮区 -->
    <div class="clock-actions">
      <el-button 
        :type="isWorking ? 'success' : 'primary'"
        :disabled="!canClockIn"
        round 
        size="large"
        @click="handleClockIn"
      >
        {{ clockInButtonText }}
      </el-button>
      <div class="location-info">
        <i class="el-icon-location"></i>
        <span>{{ currentLocation }}</span>
      </div>
    </div>

    <!-- 打卡记录 -->
    <div class="clock-records">
      <div class="title">今日打卡记录</div>
      <el-card v-if="todayRecords.length">
        <template v-for="record in todayRecords" :key="record.id">
          <div class="record-item">
            <span :class="{ 'clock-in': record.type === '上班打卡', 'clock-out': record.type === '下班打卡' }">
              {{ record.type }}
            </span>
            <span>{{ record.time }}</span>
            <span class="record-address">{{ record.address }}</span>
          </div>
        </template>
      </el-card>
      <el-empty v-else description="暂无打卡记录" />
    </div>



    
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

// 响应式数据
const currentTime = ref('')
const currentDate = ref('')
const userName = ref('')
const userAvatar = ref('https://placeholder.com/150')
const currentLocation = ref('正在获取位置...')
const canClockIn = ref(true)
const clockInButtonText = ref('上班打卡')
const todayRecords = ref([])

// 新增经纬度响应式数据
const latitude = ref('')
const longitude = ref('')

//标记是否已经上班打卡
const isWorking = ref(false)

// 获取缓存的用户信息
const userInfo = JSON.parse(sessionStorage.getItem("user"));

// 更新时间
let timer
const updateDateTime = () => {
  const now = dayjs()
  currentTime.ref = now.format('HH:mm:ss')
  currentDate.ref = now.format('YYYY年MM月DD日')
}

// 获取位置信息
const getLocation = async () => {
  try {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        position => {
          latitude.value = position.coords.latitude
          longitude.value = position.coords.longitude
          currentLocation.value = `经度：${longitude.value}，纬度：${latitude.value}`
          
          // 通过高德地图API转换为具体地址
          convertToAddress(latitude.value, longitude.value)
        },
        error => {
          switch(error.code) {
            case error.PERMISSION_DENIED:
              currentLocation.value = '用户拒绝了位置请求'
              break
            case error.POSITION_UNAVAILABLE:
              currentLocation.value = '位置信息不可用'
              break
            case error.TIMEOUT:
              currentLocation.value = '获取位置超时'
              break
            default:
              currentLocation.value = '获取位置失败'
          }
          console.error('位置获取失败：', error)
        },
        {
          enableHighAccuracy: true, // 启用高精度
          timeout: 5000,           // 超时时间：5秒
          maximumAge: 0            // 不使用缓存
        }
      )
    } else {
      currentLocation.value = '浏览器不支持地理定位'
    }
  } catch (error) {
    console.error('位置服务错误：', error)
    currentLocation.value = '获取位置发生错误'
  }
}

// 新增：获取今日打卡状态
const getTodayClockStatus = () => {
  if (todayRecords.value.length > 0) {
    const lastRecord = todayRecords.value[todayRecords.value.length - 1]
    isWorking.value = lastRecord.type === '上班打卡'
    clockInButtonText.value = isWorking.value ? '下班打卡' : '上班打卡'
  }
}

// 修改打卡处理函数
const handleClockIn = async () => {
  try {
    const now = dayjs().format('YYYY-MM-DD HH:mm:ss');
    let clockType = '';

    if (clockInButtonText.value === '上班打卡' && currentTime.value > "12:00:00") {
      clockType = '迟到';
    } else if (clockInButtonText.value === '下班打卡' && currentTime.value < '17:00:00') {
      clockType = '早退';
    } else {
      clockType = '正常打卡';
    }

    // 获取当前地址
    const address = await convertToAddress(latitude.value, longitude.value);
    
    // 添加打卡记录
    todayRecords.value.push({
      id: Date.now(),
      type: clockType,
      time: now,
      address: address
    });
    
    // 发送打卡记录到后端
    await saveAttendanceToDatabase({
      
      userid: userInfo ? userInfo.userid : null, // 使用从 sessionStorage 获取的用户 ID
      type: clockType,
      clockintime: isWorking.value ? null : now,
      clockouttime: isWorking.value ? now : null,
      location: address
    });

    // 更新状态
    isWorking.value = !isWorking.value;
    clockInButtonText.value = isWorking.value ? '下班打卡' : '上班打卡';

    ElMessage.success(`${clockType}成功！`);
  } catch (error) {
    ElMessage.error('打卡失败，请重试');
    console.error('打卡错误：', error);
  }
}

// 保存考勤记录到数据库的函数
const saveAttendanceToDatabase = async (attendanceData) => {
  try {
    const response = await fetch('http://localhost:8080/api/attendance/insert', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(attendanceData),
    });

    if (!response.ok) {
      throw new Error('网络响应不正常');
    }

    const data = await response.json();
    console.log('考勤记录保存成功：', data);
  } catch (error) {
    console.error('保存考勤记录失败：', error);
  }
}

// 修改 convertToAddress 函数以返回地址
const convertToAddress = async (latitude, longitude) => {
  try {
    const response = await fetch(`https://restapi.amap.com/v3/geocode/regeo?key=0bf9163f78e72799c1484fa1896e62b4&location=${longitude},${latitude}`);
    const data = await response.json();
    if (data && data.regeocode && data.regeocode.formatted_address) {
      return data.regeocode.formatted_address; // 返回具体地址
    } else {
      return '地址获取失败';
    }
  } catch (error) {
    console.error('地址转换错误：', error);
    return '地址获取发生错误';
  }
}

// 生命周期钩子
onMounted(() => {
  updateDateTime()
  timer = setInterval(updateDateTime, 1000)
  getLocation()
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
.clock-in-container {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.header-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40px;
}

.date-time .time {
  font-size: 36px;
  font-weight: bold;
}

.date-time .date {
  font-size: 16px;
  color: #666;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

.clock-actions {
  text-align: center;
  margin: 40px 0;
}

.location-info {
  margin-top: 10px;
  color: #666;
  font-size: 14px;
}

.clock-records {
  margin-top: 30px;
}

.clock-records .title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
}

.record-item {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.record-item:last-child {
  border-bottom: none;
}
</style>
